// @flow
import { Modal, Form, Input, message } from 'antd'
import React from 'react'
import { connect } from 'react-redux'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import md5 from 'md5'
import styles from './ChangePsw.css'
const FormItem = Form.Item

type Props = {
  userId: number
}

const CollectionCreateForm = Form.create()(
  (props) => {
    const { visible, onCancel, onOk, form } = props
    const { getFieldDecorator } = form
    return (
      <Modal
        visible={visible}
        title='修改密码'
        okText='确认'
        onCancel={onCancel}
        onOk={onOk}
      >
        <Form layout='vertical' className={styles['main']}>
          <FormItem label='原始密码'>
            {getFieldDecorator('oldPsw', {
              rules: [{ required: true, message: '请输入原始密码!' }]
            })(
              <Input type='password' />
            )}
          </FormItem>
          <FormItem label='新密码'>
            {getFieldDecorator('newPsw', {
              rules: [{ required: true, message: '请输入您的新密码!' }]
            })(
              <Input type='password' />
            )}
          </FormItem>
          <FormItem label='确认密码'>
            {getFieldDecorator('checkPsw', {
              rules: [{ required: true, message: '两次密码不一致!' }]
            })(
              <Input type='password' />
            )}
          </FormItem>
        </Form>
      </Modal>
    )
  }
)

class ChangePsw extends React.Component {
  props: Props
  state = {
    visible: false
  }
  showModal = () => {
    this.setState({ visible: true })
  }
  handleCancel = () => {
    this.setState({ visible: false })
  }
  handleChangePsw = () => {
    const form = this.form
    form.validateFields((err, values) => {
      if (err) {
        return
      }
      if (values.newPsw !== values.checkPsw) {
        message.info('两次密码不一致，请重新输入')
        form.resetFields()
        return
      }
      let userInf = Object.assign({}, values, { userId: this.props.userId })
      this.sendUserInf(userInf)
    })
  }
  sendUserInf = (userInf) => {
    const oldPsw = md5(userInf.oldPsw)
    universalFetch(`${__SERVICE_API__}sys/users/${userInf.userId}/confirmPwd?pwd=${oldPsw}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(userInf)
    })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.changePsw(userInf)
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        message.error('原始密码错误，请重新输入')
      })
  }
  changePsw = (values) => {
    const datas = {
      id: values.userId,
      password: md5(values.newPsw)
    }
    universalFetch(`${__SERVICE_API__}sys/users/${values.userId}`,
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(datas)
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('修改密码成功')
        this.setState({ visible: false })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        message.error('修改失败')
      })
  }
  saveFormRef = (form) => {
    this.form = form
  }
  render () {
    return (
      <div>
        <div type='primary' onClick={this.showModal}>修改密码</div>
        <CollectionCreateForm
          ref={this.saveFormRef}
          visible={this.state.visible}
          onCancel={this.handleCancel}
          onOk={this.handleChangePsw}
        />
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    userId: state.user.userId
  }
}
const mapDispatchToProps = {}
export default connect(mapStateToProps, mapDispatchToProps)(ChangePsw)
